package com.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.project.entity.BaseResult;
import com.project.entity.Customer;
import com.project.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
   private CustomerService customerService;
    @PostMapping("register")
    public BaseResult<String> register(HttpServletRequest request, @RequestBody Customer customer){
        log.info("用户注册信息：{}",customer.toString());
        customerService.save(customer);
        return BaseResult.ok("用户注册成功");
    }
    @PostMapping("/login")
    public BaseResult<Customer> login(HttpServletRequest request, @RequestBody Customer customer) {

        //1、获取密码
        String password = customer.getCusPassword();
        //2、根据页面提交的用户账号查询数据库
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getId, customer.getId());
        Customer cus = customerService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if (cus == null) {
            return BaseResult.fail("登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!cus.getCusPassword().equals(password)) {
            return BaseResult.fail("登录失败");
        }

        //5、登录成功，将用户id存入Session并返回登录成功结果
        request.getSession().setAttribute("customer", cus.getId());
        return BaseResult.ok(cus);
    }
    @PostMapping("/logout")
    public BaseResult<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录用户的id
        request.getSession().removeAttribute("customer");
        return BaseResult.ok("退出成功");
    }
    @PostMapping("/edit")
    public BaseResult<String> edit(@RequestBody Customer customer){
        customerService.updateById(customer);
        return BaseResult.ok("更新成功");

    }
    @PostMapping("/buy")
    public BaseResult<String> buy(HttpServletRequest request,@RequestBody Customer customer){
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        Long id = (Long) request.getSession().getAttribute("customer");
        queryWrapper.eq(Customer::getId, id);
        Customer cus = customerService.getOne(queryWrapper);
        cus.cusVip=1;
        cus.vipTime=customer.getVipTime();
        customerService.updateById(cus);
        return BaseResult.ok("会员购买成功");


    }



}
